package handler

import (
	"encoding/json"
	"repo-man/cache"
	"repo-man/models"
	"time"

	"github.com/gin-gonic/gin"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	types := c.PostForm("type")
	data := models.Area{
		Title:   title,
		Content: content,
		Types:   types,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	redis_key := "add_"
	cache.Rdb.Get(cache.Ctx, redis_key).Result()
	jsonData, _ := json.Marshal(data)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
	return
}
func List(c *gin.Context) {
	var area []models.Area
	redis_key := "list_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&area)
		jsonData, _ := json.Marshal(area)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &area)
	}
	var total int64
	models.DB.Model(models.Area{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  area,
		"total": total,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var area []models.Area
	redis_key := "list_detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).First(&area)
		jsonData, _ := json.Marshal(area)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &area)
	}
	var total int64
	models.DB.Model(models.Area{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  area,
		"total": total,
	})
	return
}
